const app = getApp()
Page({
  data: {
    userInfo: {},
    deviceId: "",
    name: "",
    services: [],
    cd01: "",
    cd02: "",
    cd03: "",
    cd04: "",
    cd05: "",
    cd06: "",
    characteristics01: null,
    characteristics02: null,
    characteristics03: null,
    characteristics04: null,
    characteristics05: null,
    characteristics06: null,
    result: "-",
    pressure: 0,
    cmd: "",
    deviceInfo: "",
    electric: "",
    progress_txt: "正在匹配中...",
    count: 0,
    countTimer: null,
    commitCount: 0,
    connected: true,
    value: 0,
    timer: null,
    gradientColor: {
      '0%': '#E6A23C',
      '100%': '#67C23A'
    }
  },
  connection: function() {
    var e = this;
    wx.createBLEConnection({
      deviceId: e.data.deviceId,
      success: function(t) {
        wx.getBLEDeviceServices({
          deviceId: e.data.deviceId,
          success: function(t) {
            console.log("device services:", t.services), 
            e.setData({ services: t.services}), 
            console.log("--------------------------------------"), 
            console.log("device设备的id:", e.data.deviceId),
            console.log("device设备的服务id:", e.data.serviceId), 
            setTimeout(function() {
              wx.getBLEDeviceCharacteristics({
                deviceId: e.data.deviceId,
                serviceId: e.data.services[0].uuid,
                success: function(t) {
                  console.log("000000000000" + e.data.serviceId), 
                  console.log("device getBLEDeviceCharacteristics:", t.characteristics);
                  for (var a = 0; a < 5; a++) -1 != t.characteristics[a].uuid.indexOf("05") && e.setData({
                    cd05: t.characteristics[a].uuid,
                    characteristics05: t.characteristics[a]
                  }), 
                  -1 != t.characteristics[a].uuid.indexOf("02") && e.setData({
                    cd02: t.characteristics[a].uuid,
                    characteristics02: t.characteristics[a]
                  });
                  wx.onBLECharacteristicValueChange(function(t) {
                    var a = t.value,
                    i = e.buf2hex(a);
                    // console.log(i), 
                    "ffff0a02" == i.substring(2, 10) ? 
                    e.setData({
                      result: "设备充气　" + e.analysisAirInflationData(i.substring(10, 22))
                    }) : 
                    "ffff0504f7" == i.substring(2, i.length) ? e.setData({
                      result: "设备端取消测量"
                    }) : 
                    "ffff0505f6" == i.substring(2, i.length) ? e.setData({
                      result: "客户端取消测量"
                    }) : 
                    "ffff0607" == i.substring(2, 10) ? e.setData({
                      result: "测量错误"
                    }) : 
                    "ffff4903" == i.substring(2, 10) ? e.analysisResult(i.substring(10, 18)) : 
                    "ffff0609" == i.substring(2, 10) ? e.setData({
                      electric: parseInt(("0x" + i.substring(10, 12)).toString(10))
                    }) : "ffff0708" == i.substring(2, 10) && e.setData({
                      deviceInfo: e.analysisDeviceInfoData(i.substring(10, 16))
                    });
                  }), 
                  wx.notifyBLECharacteristicValueChange({
                    deviceId: e.data.deviceId,
                    serviceId: e.data.services[0].uuid,
                    characteristicId: e.data.cd02,
                    state: !0,
                    success: function(t) {
                      console.log("notifyBLECharacteristicValueChange success", t), e.setData({
                        result: "设备连接成功,可以开始测量"
                      }), setTimeout(e.bindViewTap, 1000);
                    },
                    fail: function(e) {},
                    complete: function(e) {}
                  });
                },
                fail: function(e) {
                  console.log("fail" + e);
                }
              });
            }, 2000);
          }
        });
      },
      fail: function(e) {},
      complete: function(e) {}
    });
  },
  // 开始测量指令
  bindViewTap: function () {
    var e = this,
      t = "FFFF0501FA",
      a = new Uint8Array(t.match(/[\da-f]{2}/gi).map(function (e) {
        return parseInt(e, 16);
      }));
    console.log("typedArray" + a);
    var i = a.buffer;
    console.log("buffer1" + i), e.setData({
      cmd: t
    }), wx.writeBLECharacteristicValue({
      deviceId: e.data.deviceId,
      serviceId: e.data.services[0].uuid,
      characteristicId: e.data.cd05,
      value: i,
      success: function (e) {
        console.log("success  发送 开始测量指令" + e);
      },
      fail: function (e) {
        console.log("fail  发送 开始测量指令" + e);
      },
      complete: function (e) { }
    });
  },
  // 取消测量
  bindViewTap02: function () {
    console.log('点了取消')
    var e = this,
    t = "FFFF0504F7",
    a = new Uint8Array(t.match(/[\da-f]{2}/gi).map(function (e) {
      return parseInt(e, 16);
    }));
    console.log("typedArray" + a);
    var i = a.buffer;
    console.log("buffer1" + i), e.setData({
      cmd: t
    }), 0 != e.data.services.length && wx.writeBLECharacteristicValue({
      deviceId: e.data.deviceId,
      serviceId: e.data.services[0].uuid,
      characteristicId: e.data.cd05,
      value: i,
      success: function (e) {
        console.log("success  取消指令发送成功" + e);
      },
      fail: function (e) {
        console.log("fail  指令发送fail" + e);
      },
      complete: function (e) { }
      }), wx.redirectTo({
      url: "../jinrixueya/jinrixueya"
    });
  },
  onLoad: function(t) {
    wx.hideShareMenu();
    var a = this;
    console.log("deviceId=" + t.deviceId), console.log("name=" + t.name), a.setData({
      deviceId: t.deviceId,
      name: t.name
    }), a.connection();
  },
  onUnload: function () {
    var e = this;
    wx.closeBLEConnection({
      deviceId: e.data.deviceId,
      success: function (e) {
        console.log(e);
      }
    }), wx.closeBluetoothAdapter(function (e) {
      console.log("关闭蓝牙模块" + e);
    });
  },
  onReady: function() {

  },
  onShow: function() {

  },
  onHide: function() {

  },
  
  analysisAirInflationData: function (e) {
    var t = this,
      a = t.repair(parseInt("0x" + e.substring(4, 8)).toString(2) + "") + t.repair(parseInt("0x" + e.substring(2, 4)).toString(2) + ""),
      i = t.repair(parseInt("0x" + e.substring(10, 12)).toString(2) + "") + t.repair(parseInt("0x" + e.substring(8, 10)).toString(2) + "");
      console.log(a)
    console.log('气压：' + parseInt(a, 2))
    return parseInt(a, 2) <= 255 && t.setData({
      pressure: parseInt(a, 2)
    }), "压力：" + parseInt(a, 2) + "　脉搏：" + parseInt(i, 2) + "　心跳:" + parseInt(e.substring(0, 2));
    
  },
  analysisResult: function (e) {
    var t = parseInt(("0x" + e.substring(0, 2)).toString(10)),
      a = parseInt(("0x" + e.substring(2, 4)).toString(10)) + 30,
      i = parseInt(("0x" + e.substring(4, 6)).toString(10)) + 30,
      s = parseInt(e.substring(6, 8)),
      c = this;
    if (0 == c.data.commitCount) {
      var n = require("../../utils/util.js");
      // console.log('bloodPressureOpen----', i)
      // console.log('bloodPressureClose----', a)
      // console.log('pulse----', t)
      // console.log('arrhythmia----', s)
      // console.log('equipment_version---', 'LD-563')
      // console.log('type---', '1')
      // console.log('measureTime---', n.formatTime(new Date()))
      // console.log('equipmentNo---', c.data.deviceId.replace(/:/g, ""))
      wx.redirectTo({
        url: "../result/result?deviceId=" + c.data.deviceId + "&bloodPressureOpen=" + i + "&bloodPressureClose=" + a + "&pulse=" + t + "&arrhythmia=" + s + "&equipment_version=LD-563&type=1&measureTime=" + n.formatTime(new Date()) + "&equipmentNo=" + c.data.deviceId.replace(/:/g, ""),
        success: function (e) { },
        fail: function (e) { },
        complete: function (e) { }
      });
    }
    return c.data.commitCount++ , "心率：" + t + '　' + "收缩压：" + a + '　' + "舒张压：" + i + '　' + "心率不齐：" + s;
  },
  analysisDeviceInfoData: function (e) {
    return "机型：" + parseInt(("0x" + e.substring(0, 2)).toString(10)) + "版本号：" + parseInt(("0x" + e.substring(2, 4)).toString(10));
  },
  buf2hex: function (e) {
    return Array.prototype.map.call(new Uint8Array(e), function (e) {
      return ("00" + e.toString(16)).slice(-2);
    }).join("");
  },
  repair: function (e) {
    for (; e.length < 8;) e = "0" + e;
    return e;
  },
  /*转换成需要的格式*/
  buf2string(buffer) {
    var arr = Array.prototype.map.call(new Uint8Array(buffer), x => x)
    return arr.map((char, i) => {
      return String.fromCharCode(char);
    }).join('');
  },
  receiveData(buf) {
    return this.hexCharCodeToStr(this.ab2hex(buf))
  },
  /*转成二进制*/
  ab2hex(buffer) {
    var hexArr = Array.prototype.map.call(
      new Uint8Array(buffer),
      function(bit) {
        return ('00' + bit.toString(16)).slice(-2)
      }
    )
    return hexArr.join('')
  },
  /*转成可展会的文字*/
  hexCharCodeToStr(hexCharCodeStr) {
    var trimedStr = hexCharCodeStr.trim();
    var rawStr = trimedStr.substr(0, 2).toLowerCase() === '0x' ? trimedStr.substr(2) : trimedStr;
    var len = rawStr.length;
    var curCharCode;
    var resultStr = [];
    for (var i = 0; i < len; i = i + 2) {
      curCharCode = parseInt(rawStr.substr(i, 2), 16);
      resultStr.push(String.fromCharCode(curCharCode));
    }
    return resultStr.join('');
  }
})